<?php

namespace APP\Ctrl;
use CMS\Ctrl as Base;
use CMS\Helper as Helper;

class Ranks extends Base {
	private $separator = '-_++_-';

	// construct
	public function run() {
		// set permissions
		$this->permissions();

		// manage uri paths
		if(count($this->uri) > 0) {
			@list($func, $id) = $this->uri;
			$this->$func($id ? $id : '0-null');
		} else $this->index();
	}

	// permissions
	private function permissions() {
		// not logged in? don't bother
		if(!isset($this->session->auth))
			die(new Error());

		// no root access?
		if(!(isset($this->session->auth['permissions']['root']) && $this->session->auth['permissions']['root'] == 1))
			die(new Error());
	}

	// show all ranks
	public function index() {
		$this->view->func = 'index';

		// set title
		$this->view->title = $this->settings['blizz_guild'] . ' - Console / Ranks';

		// find the ranks
		$result = $this->db->query("SELECT
			r.id, r.name,
			GROUP_CONCAT(u.id, '{$this->separator}') AS concate_id,
			GROUP_CONCAT(u.name, '{$this->separator}') AS concate_name

			FROM ranks AS r
			LEFT JOIN users AS u ON u.rank = r.id

		GROUP BY r.id
		ORDER BY LENGTH(r.permissions) DESC");

		// transform
		$data = array();
		while($res = $result->fetchArray(SQLITE3_ASSOC)) {
			$data[] = array(
				'id' => $res['id'],
				'name' => $res['name'],
				'link' => $res['id'] . '-' . Helper::generate_named_id($res['name']),
				'listing' => $this->listing($res['concate_id'], $res['concate_name'])
			);
		}

		// output data
		$this->view->data = $data;

		// set path
		$this->view->path = array(
			'func' => $this->view->func
		);
	}

	// get a listing of members
	private function listing($ids, $names) {
		// get me arrays
		$ids = explode($this->separator, $ids);
		$names = explode($this->separator, $names);

		// default
		$data = array();

		// not the same? wtf
		if(count($ids) != count($names))
			return $data;

		// match each
		for($i = 0; $i < count($ids); $i++) {
			// empty?
			if(empty($ids[$i]) || empty($names[$i]))
				return $data;

			// compile list
			$data[] = array(
				'id' => $ids[$i],
				'name' => $names[$i],
				'link' => $ids[$i] . '-' . Helper::generate_named_id($names[$i])
			);
		}

		return $data;
	}

	// create new rank
	public function create($id) {
		$this->view->func = 'create';

		// send rank to view
		$this->view->rank = array(
			'id' => 0,
			'name' => 'New Rank'
		);

		// set title
		$this->view->title = $this->settings['blizz_guild'] . ' - Cosnole / Ranks / ' . $this->view->rank['name'];

		// send categories to view
		$this->view->cats = $this->categories();

		// set path
		$this->view->path = array(
			'func' => $this->view->func
		);
	}

	// edit a rank
	public function edit($id) {
		$this->view->func = 'edit';

		// prepare vars
		$id = explode("-", $id, 2);
		$id = $this->db->escapeString((int)reset($id));

		// get rank
		$rank = $this->db->querySingle("SELECT id, name, permissions FROM ranks WHERE id = '{$id}'", true);
		if(!$rank)
			die(new Error());

		// set title
		$this->view->title = $this->settings['blizz_guild'] . ' - Console / Ranks / ' . $rank['name'];

		// send rank to view
		$rank['permissions'] = unserialize($rank['permissions']);
		$this->view->rank = $rank;

		// send categories to view
		$this->view->cats = $this->categories();

		// set path
		$this->view->path = array(
			'func' => $this->view->func
		);
	}

	// get the forum categories
	private function categories() {
		// query
		$result = $this->db->query("SELECT id, name, type FROM categories ORDER BY position");

		// transform
		$data = array();
		while($res = $result->fetchArray(SQLITE3_ASSOC)) {
			$data[] = array(
				'id' => $res['id'],
				'name' => $res['name'],
				'type' => $res['type'],
				'link' => $res['id'] . '-' . Helper::generate_named_id($res['name']),
			);
		}

		// output categories
		return $data;
	}

	// the save function
	public function save() {
		// get vars
		$token = $this->request->post('token', 'int');
		$name = $this->request->post('name');
		$root = $this->request->post('root', 'int');
		$forum = $this->request->post('forum', 'array');
		if(is_null($token) || is_null($name) || is_null($root))
			return $this->json = array('success' => false);

		// prepare vars
		$token = $this->db->escapeString($token);
		$name = $this->db->escapeString($name);

		// build permissions
		$permissions = $this->db->escapeString(serialize(array(
			'root' => $root == 1 ? 1 : NULL,
			'forum' => $forum
		)));

		// insert
		if($token == 0)
			$this->db->exec("INSERT INTO ranks (name, permissions)
				VALUES ('{$name}', '{$permissions}')");

		// update
		else $this->db->exec("UPDATE ranks SET name='{$name}', permissions ='{$permissions}' WHERE id = '{$token}'");

		// return success
		return $this->json = array('success' => true);
	}

	// move members to other ranks
	public function move() {
		// get vars
		$id = $this->request->post('id', 'int');
		$to = $this->request->post('to', 'int');
		if(is_null($id) || is_null($to))
			return $this->json = array('success' => false);

		// prepare vars
		$id = $this->db->escapeString($id);
		$to = $this->db->escapeString($to);

		// move users to specified rank
		$user = $this->db->querySingle("SELECT id, password FROM users WHERE id = '{$id}'", true);
		$this->db->exec("UPDATE users SET rank='{$to}' WHERE id = '{$id}'");

		// compile the token
		$tokens = array(base64_encode(strlen($user['id']) . $user['id'] . $user['password']));

		// return success
		return $this->json = array('success' => true,
			'tokens' => $tokens
		);
	}

	// delete a rank
	public function delete() {
		// get vars
		$id = $this->request->post('id', 'int');
		if(is_null($id))
			return $this->json = array('success' => false);

		// prepare vars
		$id = $this->db->escapeString($id);
		$default = $this->settings['rank_apply'];

		// get tokens
		$result = $this->db->query("SELECT id, password FROM users WHERE rank = '{$id}'");

		// transform
		$tokens = array();
		while($res = $result->fetchArray(SQLITE3_ASSOC))
			$tokens[] = base64_encode(strlen($res['id']) . $res['id'] . $res['password']);

		// move users
		$this->db->exec("UPDATE users SET rank='{$default}' WHERE rank = '{$id}'");
		$count = $this->db->changes();

		// delete rank
		$this->db->exec("DELETE FROM ranks WHERE id = '{$id}'");

		// return success + affected rows
		return $this->json = array('success' => true,
			'changes' => $count,
			'tokens' => $tokens
		);
	}
}